﻿using System.Collections.Generic;
using System.Linq;
using System.Net;
using UnityEngine;

public class CapsuleDetection : Detection
{
    public Transform StartPoint;
    public Transform EndPoint;
    public float Radius;

    public bool debug;

    private void OnDrawGizmos()
    {
        if (debug && StartPoint != null && EndPoint != null)
        {
            Vector3 direction = EndPoint.position - StartPoint.position;
            float length = direction.magnitude;
            direction.Normalize();
            if (length > 0) 
            {
                Gizmos.color = Color.yellow;
                Gizmos.DrawWireSphere(StartPoint.position, Radius);
                Gizmos.DrawWireSphere(EndPoint.position, Radius);
                Vector3 perpendicual = Vector3.Cross(direction, Vector3.up).normalized;
                Gizmos.DrawLine(StartPoint.position + perpendicual * Radius, EndPoint.position + perpendicual * Radius);
                Gizmos.DrawLine(StartPoint.position - perpendicual * Radius, EndPoint.position - perpendicual * Radius);
                perpendicual = Vector3.Cross(perpendicual, direction).normalized;
                Gizmos.DrawLine(StartPoint.position + perpendicual * Radius, EndPoint.position + perpendicual * Radius);
                Gizmos.DrawLine(StartPoint.position - perpendicual * Radius, EndPoint.position - perpendicual * Radius);
            }
        }
    }

    public override List<Collider> GetDetection()
    {
        List<Collider> result = new List<Collider>();
        Collider[] hits = Physics.OverlapCapsule(StartPoint.position, EndPoint.position, Radius);
        foreach (Collider hit in hits) 
        {
            AgentHitBox hitBox;
            if(hit.TryGetComponent(out hitBox)
                &&hitBox.Agent
                &&targetTags.Contains(hitBox.Agent.tag)
                &&!wasHitList.Contains(hitBox.Agent)) 
            {
                wasHitList.Add(hitBox.Agent);
                result.Add(hit);
            }
        }
        return result;
    }
}

